#This makes the same as layers_manager.py but using the agregator located in the apps folder

from libs.channel11870.Channel11870 import Channel11870
from libs.channelPanoramio.ChannelPanoramio import ChannelPanoramio
from libs.channelYoutube.ChannelYoutube import ChannelYoutube
from social.layers.InternalLayer import InternalLayer
from apps.agregator.views import *
from settings import BASEDIR 

from os import path 

CHANNELS_SUPPORTED= { "11870" : "Channel11870(\"\")",
                      "panoramio" : "ChannelPanoramio(\"\")",
                      "geonames" : "ChannelGeonames(\"\")",
                      "youtube" : "ChannelYoutube(\"\")"}

DESCRIPTIONS= { "11870" : "11870 channel: channel to make searches in the portal http://11870.com, with information about places, restaurants, ocio...",
                      "panoramio" : "Panoramio channel: this channel makes use of the portal http://panoramio.com to return a list of geolocated photos",
                      "geonames" : "Geonames channel: channel to make searches in the portal http://www.geonames.com, with information about places",
                      "youtube" : "Youtube channel: allow users to search geolocated videos"}

ICONS_PATH = path.join(BASEDIR, "social", "site_media", "layers", "icons")

def layers_request(layer_id, search, options):
    
    if layer_id in CHANNELS_SUPPORTED:
        #channel = eval(CHANNELS_SUPPORTED[layer_id]   )
        petition ={'channel' : str(layer_id), 'text' : str(search)}
        for field in options:
            petition[field] = options[field]
        success, response = layer_node_request(petition)
        if success:
            return success, response
        else:
            return success, response    
#        success, result = channel.set_options(options)
#        if success:
#            channel.set_search_pattern(search)
#            success, nodesList = channel.process()
#            return success, nodesList
#        else:
#            return success, result
    elif layer_id == "lgs":

        lgs = InternalLayer()

        success, result = lgs.set_options(options)
        if success:
            lgs.set_search_pattern(search)
            success, nodesList = lgs.process()
            return success, nodesList
        else:
            return success, result
        
    else:
        return False, "Channel not supported"
    
         
def layers_info(layer_id):
    if layer_id in CHANNELS_SUPPORTED:
        return True, DESCRIPTIONS[layer_id]

    elif layer_id == "lgs":
        lgs = InternalLayer()
        return True, lgs.get_info() 
    else:
        return False, "Channel not supported"   


def layers_icon(layer_id):
    
    try:
        url = path.join( ICONS_PATH , layer_id + ".png")
        image_data = open(url, "rb").read()
        return True, image_data 
    except ValueError:
        return False, "Error retrieving icon"